#import "EGORefreshTableTopicView.h"

#define TEXT_COLOR	 [UIColor colorWithRed:87.0/255.0 green:108.0/255.0 blue:137.0/255.0 alpha:1.0]
#define FLIP_ANIMATION_DURATION 0.18f

#define  RefreshTopicHight 45.0f

@interface EGORefreshTableTopicView (Private)
- (void)setState:(EGOTopicPullRefreshState)aState;
@end

@implementation EGORefreshTableTopicView

@synthesize delegate=_delegate;

- (id)initWithFrame:(CGRect)frame textColor:(UIColor *)textColor  {
    if((self = [super initWithFrame:frame])) {
		self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
		self.backgroundColor = [UIColor colorWithRed:226.0/255.0 green:231.0/255.0 blue:237.0/255.0 alpha:1.0];

		UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, frame.size.height - 52.0f, self.frame.size.width, 20.0f)];
		label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
		label.font = [UIFont systemFontOfSize:12.0f];
		label.textColor = textColor;
		label.shadowColor = [UIColor colorWithWhite:0.9f alpha:1.0f];
		label.shadowOffset = CGSizeMake(0.0f, 1.0f);
		label.backgroundColor = [UIColor clearColor];
		label.textAlignment = UITextAlignmentCenter;
		[self addSubview:label];
		_lastUpdatedLabel=label;
		[label release];
		
		label = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, frame.size.height - 30.0f, self.frame.size.width, 20.0f)];
		label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
		label.font = [UIFont boldSystemFontOfSize:13.0f];
		label.textColor = textColor;
		label.shadowColor = [UIColor colorWithWhite:0.9f alpha:1.0f];
		label.shadowOffset = CGSizeMake(0.0f, 1.0f);
		label.backgroundColor = [UIColor clearColor];
		label.textAlignment = UITextAlignmentCenter;
		[self addSubview:label];
		_statusLabel=label;
		[label release];
		
//		CALayer *layer = [CALayer layer];
//		layer.frame = CGRectMake(25.0f, frame.size.height - 65.0f, 30.0f, 55.0f);
//		layer.contentsGravity = kCAGravityResizeAspect;
//		layer.contents = (id)[UIImage imageNamed:arrow].CGImage;
//		
//#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000
//		if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
//			layer.contentsScale = [[UIScreen mainScreen] scale];
//		}
//#endif
//		[[self layer] addSublayer:layer];
//		_arrowImage=layer;
		
//		UIActivityIndicatorView *view = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
//		view.frame = CGRectMake(25.0f, frame.size.height - 38.0f, 20.0f, 20.0f);
//		[self addSubview:view];
//		_activityView = view;
//		[view release];
        
        UIImageView *view = [[UIImageView alloc] initWithFrame:CGRectMake(25.0f, frame.size.height - 38.0f, 30.0f, 30.0f) ];
        view.image = [UIImage imageNamed:@"fan_1.png"];
        [self addSubview:view];
        _indicator = view;
        _indicator.alpha = 0.0f;
		[view release];
		
		[self setState:EGOTOPICPullRefreshNormal];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame  {
  return [self initWithFrame:frame textColor:TEXT_COLOR];
}

#pragma mark -
#pragma mark Setters

- (void)refreshLastUpdatedDate {
	if ([_delegate respondsToSelector:@selector(egoRefreshTableTopicDataSourceLastUpdated:)]) {
		NSDate *date = [_delegate egoRefreshTableTopicDataSourceLastUpdated:self];
		[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehaviorDefault];
		NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
		[dateFormatter setDateStyle:NSDateFormatterShortStyle];
		[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
        _lastUpdatedLabel.text = [NSString stringWithFormat:@"上次更新: %@", [dateFormatter stringFromDate:date]];
		[[NSUserDefaults standardUserDefaults] setObject:_lastUpdatedLabel.text forKey:@"EGORefreshTableView_LastRefresh"];
		[[NSUserDefaults standardUserDefaults] synchronize];
	} else {
		_lastUpdatedLabel.text = nil;
	}
}

- (void)setState:(EGOTopicPullRefreshState)aState{
	switch (aState) {
		case EGOTOPICPullRefreshPulling:
            _statusLabel.text = NSLocalizedString(@"好了松开吧", @"Release");
//			[CATransaction begin];
//			[CATransaction setAnimationDuration:FLIP_ANIMATION_DURATION];
//			_arrowImage.transform = CATransform3DMakeRotation((M_PI / 180.0) * 180.0f, 0.0f, 0.0f, 1.0f);
//			[CATransaction commit];
			break;
		case EGOTOPICPullRefreshNormal:
//			if (_state == EGOTOPICPullRefreshPulling) {
//				[CATransaction begin];
//				[CATransaction setAnimationDuration:FLIP_ANIMATION_DURATION];
//				_arrowImage.transform = CATransform3DIdentity;
//				[CATransaction commit];
//			}
            _statusLabel.text = NSLocalizedString(@"制冷", @"Keep Going");
            [_indicator stopAnimating];
//			[_activityView stopAnimating];
//			[CATransaction begin];
//			[CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
//			_arrowImage.hidden = NO;
//			_arrowImage.transform = CATransform3DIdentity;
//			[CATransaction commit];
			[self refreshLastUpdatedDate];
			break;
		case EGOTOPICPullRefreshLoading:
            _statusLabel.text = NSLocalizedString(@"正在努力制冷", @"It is a ...");
            _indicator.animationDuration = 0.4;
            _indicator.animationImages = [NSArray arrayWithObjects:
                                         [UIImage imageNamed:@"fan_1.png"],
                                         [UIImage imageNamed:@"fan_2.png"],
                                         [UIImage imageNamed:@"fan_3.png"],
                                         [UIImage imageNamed:@"fan_4.png"],
                                         [UIImage imageNamed:@"fan_5.png"],
                                         [UIImage imageNamed:@"fan_6.png"],
                                         [UIImage imageNamed:@"fan_7.png"],
                                         [UIImage imageNamed:@"fan_8.png"],
                                         nil];
            [_indicator startAnimating];
//			[_activityView startAnimating];
//			[CATransaction begin];
//			[CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
//			_arrowImage.hidden = YES;
//			[CATransaction commit];
			break;
		default:
			break;
	}
	_state = aState;
}

#pragma mark -
#pragma mark ScrollView Methods

- (void)egoRefreshScrollViewDidScroll:(UIScrollView *)scrollView {
//    Log(@"MARK %f %f",scrollView.contentOffset.x, scrollView.contentOffset.y);
    int tmpA = (abs(scrollView.contentOffset.y)>=60?59:abs(scrollView.contentOffset.y))/6 + 1;
    if( tmpA != alpha){
        alpha = tmpA;
//        Log(@"MARK %d %f",tmpA, scrollView.contentOffset.y);
        _indicator.alpha = 0.1f * alpha;
    }
	if (_state == EGOTOPICPullRefreshLoading) {
		CGFloat offset = MAX(scrollView.contentOffset.y * -1, 0);
		offset = MIN(offset, 60);
		scrollView.contentInset = UIEdgeInsetsMake(offset, 0.0f, 0.0f, 0.0f);
	} else if (scrollView.isDragging) {
		BOOL _loading = NO;
        int tmpR = 8 - ((int)(abs(scrollView.contentOffset.y)/4)%8);
        if( tmpR != rolling){
            rolling = tmpR;
//            Log(@"MARK %d %f",tmpR, scrollView.contentOffset.y);
            _indicator.image = [UIImage imageNamed:[NSString stringWithFormat:@"fan_%d.png",rolling]];
        }
		if ([_delegate respondsToSelector:@selector(egoRefreshTableTopicDataSourceIsLoading:)]) {
			_loading = [_delegate egoRefreshTableTopicDataSourceIsLoading:self];
		}
		if (_state == EGOTOPICPullRefreshPulling && scrollView.contentOffset.y > -RefreshTopicHight && scrollView.contentOffset.y < 0.0f && !_loading) {
			[self setState:EGOTOPICPullRefreshNormal];
		} else if (_state == EGOTOPICPullRefreshNormal && scrollView.contentOffset.y < -RefreshTopicHight && !_loading) {
			[self setState:EGOTOPICPullRefreshPulling];
		}
		if (scrollView.contentInset.top != 0) {
			scrollView.contentInset = UIEdgeInsetsZero;
		}
	}
}

- (void)egoRefreshScrollViewDidEndDragging:(UIScrollView *)scrollView {
	BOOL _loading = NO;
	if ([_delegate respondsToSelector:@selector(egoRefreshTableTopicDataSourceIsLoading:)]) {
		_loading = [_delegate egoRefreshTableTopicDataSourceIsLoading:self];
	}
	if (scrollView.contentOffset.y <= -RefreshTopicHight && !_loading) {
		if ([_delegate respondsToSelector:@selector(egoRefreshTableTopicDidTriggerRefresh:)]) {
			[_delegate egoRefreshTableTopicDidTriggerRefresh:self];
		}
		[self setState:EGOTOPICPullRefreshLoading];
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:0.2];
		scrollView.contentInset = UIEdgeInsetsMake(60.0f, 0.0f, 0.0f, 0.0f);
		[UIView commitAnimations];
	}
}

- (void)egoRefreshScrollViewDataSourceDidFinishedLoading:(UIScrollView *)scrollView {
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:.3];
	[scrollView setContentInset:UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f)];
	[UIView commitAnimations];
	[self setState:EGOTOPICPullRefreshNormal];
}

#pragma mark -
#pragma mark Dealloc

- (void)dealloc {
	_delegate=nil;
//	_activityView = nil;
	_statusLabel = nil;
//	_arrowImage = nil;
	_lastUpdatedLabel = nil;
    _indicator = nil;
    [super dealloc];
}

@end
